package de.gwtprime.client;

import com.google.gwt.appengine.channel.client.Channel;
import com.google.gwt.appengine.channel.client.ChannelError;
import com.google.gwt.appengine.channel.client.ChannelFactory;
import com.google.gwt.appengine.channel.client.ChannelFactoryImpl;
import com.google.gwt.appengine.channel.client.SocketListener;
import com.google.gwt.user.client.rpc.AsyncCallback;

import de.gwtprime.client.event.OrderProcessedEvent;
import de.gwtprime.client.event.channel.TransactionUpdateAvailableEvent;

public class ChannelManagerClient {

	private ClientFactory clientFactory;

	public ChannelManagerClient(ClientFactory clientFactory) {

		this.clientFactory = clientFactory;

		this.clientFactory.getPrimeService().getChannelToken(clientFactory.getUser().getId(), new AsyncCallback<String>() {

			@Override
			public void onSuccess(String result) {
				createNewChannel(result);
			}

			@Override
			public void onFailure(Throwable caught) {
				// TODO what to do if token could not be loaded?
			}

		});
	}

	/**
	 * 
	 * @param result
	 */
	private void createNewChannel(String result) {
		ChannelFactory cf = new ChannelFactoryImpl();

		Channel c = cf.createChannel(result);
		c.open(new SocketListener() {
			@Override
			public void onOpen() {
			}
			@Override
			public void onMessage(String message) {
				
				if(message.startsWith("newTransactionAvailable")){
					clientFactory.getEventBus().fireEvent(new TransactionUpdateAvailableEvent());
				}
				 // new order created / open order processed (bought, sold)
				if(message.startsWith("orderProcessed"))
					clientFactory.getEventBus().fireEvent(new OrderProcessedEvent(null));
				
				clientFactory.getNotificationCenter().showMessage(message);
			}
			@Override
			public void onError(ChannelError error) {
			}
			@Override
			public void onClose() {
			}
		});
	}
}
